const express = require('express');
const router = express.Router();
const Chat = require('../models/Chat');
const { authenticateToken } = require('../middleware/auth');

// 所有聊天相关接口都需要认证
router.use(authenticateToken);

/**
 * 获取用户会话列表
 * GET /chat/conversations
 */
router.get('/conversations', async (req, res) => {
  try {
    console.log(`[${new Date().toISOString()}] 获取会话列表请求:`, {
      userId: req.user.userId,
      ip: req.ip || req.connection.remoteAddress
    });

    const conversations = await Chat.getConversations(req.user.userId);
    
    res.json({
      code: 200,
      message: '获取会话列表成功',
      data: {
        conversations
      }
    });
  } catch (error) {
    console.error('获取会话列表失败:', error);
    res.status(500).json({
      code: 500,
      message: error.message || '获取会话列表失败'
    });
  }
});

/**
 * 获取或创建与指定好友的会话
 * POST /chat/conversations
 * Body: { friendId: string }
 */
router.post('/conversations', async (req, res) => {
  try {
    const { friendId } = req.body;
    
    // 参数验证
    if (!friendId) {
      return res.status(400).json({
        code: 400,
        message: '好友ID不能为空'
      });
    }
    
    if (friendId === req.user.userId) {
      return res.status(400).json({
        code: 400,
        message: '不能与自己创建会话'
      });
    }

    console.log(`[${new Date().toISOString()}] 创建会话请求:`, {
      userId: req.user.userId,
      friendId,
      ip: req.ip || req.connection.remoteAddress
    });

    const conversation = await Chat.getOrCreateConversation(req.user.userId, friendId);
    
    res.json({
      code: 200,
      message: '获取会话成功',
      data: {
        conversation
      }
    });
  } catch (error) {
    console.error('创建会话失败:', error);
    
    if (error.message === '只能与好友创建会话') {
      return res.status(403).json({
        code: 403,
        message: error.message
      });
    }
    
    res.status(500).json({
      code: 500,
      message: error.message || '创建会话失败'
    });
  }
});

/**
 * 获取指定会话的详情
 * GET /chat/conversations/:conversationId
 */
router.get('/conversations/:conversationId', async (req, res) => {
  try {
    const { conversationId } = req.params;
    
    // 参数验证
    if (!conversationId || isNaN(conversationId)) {
      return res.status(400).json({
        code: 400,
        message: '会话ID无效'
      });
    }

    console.log(`[${new Date().toISOString()}] 获取会话详情请求:`, {
      userId: req.user.userId,
      conversationId,
      ip: req.ip || req.connection.remoteAddress
    });

    const conversation = await Chat.getConversationDetail(parseInt(conversationId), req.user.userId);
    
    res.json({
      code: 200,
      message: '获取会话详情成功',
      data: {
        conversation
      }
    });
  } catch (error) {
    console.error('获取会话详情失败:', error);
    
    if (error.message === '会话不存在或无权限') {
      return res.status(404).json({
        code: 404,
        message: error.message
      });
    }
    
    res.status(500).json({
      code: 500,
      message: error.message || '获取会话详情失败'
    });
  }
});

/**
 * 在指定会话中发送消息
 * POST /chat/conversations/:conversationId/messages
 * Body: { content: string }
 */
router.post('/conversations/:conversationId/messages', async (req, res) => {
  try {
    const { conversationId } = req.params;
    const { content } = req.body;
    
    // 参数验证
    if (!conversationId || isNaN(conversationId)) {
      return res.status(400).json({
        code: 400,
        message: '会话ID无效'
      });
    }
    
    if (!content || content.trim().length === 0) {
      return res.status(400).json({
        code: 400,
        message: '消息内容不能为空'
      });
    }
    
    if (content.length > 1000) {
      return res.status(400).json({
        code: 400,
        message: '消息内容不能超过1000个字符'
      });
    }

    console.log(`[${new Date().toISOString()}] 发送消息请求:`, {
      userId: req.user.userId,
      conversationId,
      contentLength: content.length,
      ip: req.ip || req.connection.remoteAddress
    });

    const message = await Chat.sendMessage(parseInt(conversationId), req.user.userId, content.trim());
    
    res.json({
      code: 200,
      message: '发送消息成功',
      data: {
        message
      }
    });
  } catch (error) {
    console.error('发送消息失败:', error);
    
    if (error.message === '会话不存在或无权限') {
      return res.status(404).json({
        code: 404,
        message: error.message
      });
    }
    
    res.status(500).json({
      code: 500,
      message: error.message || '发送消息失败'
    });
  }
});

/**
 * 获取指定会话的消息列表
 * GET /chat/conversations/:conversationId/messages
 * Query: page=1&limit=20
 */
router.get('/conversations/:conversationId/messages', async (req, res) => {
  try {
    const { conversationId } = req.params;
    const { page = 1, limit = 20 } = req.query;
    
    // 参数验证
    if (!conversationId || isNaN(conversationId)) {
      return res.status(400).json({
        code: 400,
        message: '会话ID无效'
      });
    }
    
    const pageNum = parseInt(page);
    const limitNum = parseInt(limit);
    
    if (pageNum < 1 || limitNum < 1 || limitNum > 100) {
      return res.status(400).json({
        code: 400,
        message: '分页参数无效（页码>=1，每页数量1-100）'
      });
    }

    console.log(`[${new Date().toISOString()}] 获取消息列表请求:`, {
      userId: req.user.userId,
      conversationId,
      page: pageNum,
      limit: limitNum,
      ip: req.ip || req.connection.remoteAddress
    });

    const result = await Chat.getMessages(parseInt(conversationId), req.user.userId, pageNum, limitNum);
    
    res.json({
      code: 200,
      message: '获取消息列表成功',
      data: result
    });
  } catch (error) {
    console.error('获取消息列表失败:', error);
    
    if (error.message === '会话不存在或无权限') {
      return res.status(404).json({
        code: 404,
        message: error.message
      });
    }
    
    res.status(500).json({
      code: 500,
      message: error.message || '获取消息列表失败'
    });
  }
});

/**
 * 删除指定会话
 * DELETE /chat/conversations/:conversationId
 */
router.delete('/conversations/:conversationId', async (req, res) => {
  try {
    const { conversationId } = req.params;
    
    // 参数验证
    if (!conversationId || isNaN(conversationId)) {
      return res.status(400).json({
        code: 400,
        message: '会话ID无效'
      });
    }

    console.log(`[${new Date().toISOString()}] 删除会话请求:`, {
      userId: req.user.userId,
      conversationId,
      ip: req.ip || req.connection.remoteAddress
    });

    await Chat.deleteConversation(parseInt(conversationId), req.user.userId);
    
    res.json({
      code: 200,
      message: '删除会话成功'
    });
  } catch (error) {
    console.error('删除会话失败:', error);
    
    if (error.message === '会话不存在或无权限') {
      return res.status(404).json({
        code: 404,
        message: error.message
      });
    }
    
    res.status(500).json({
      code: 500,
      message: error.message || '删除会话失败'
    });
  }
});

module.exports = router;